class BaseEditMaster {
    constructor(dataId, currentTaskPrivileges, nextTaskPrivileges, pageStatus, pageListData,
            returnUrl, fetchDataUrl, saveUrl, exportUrl, printUrl) {
        this.dataId = dataId;                                   // 当前数据标识
        this.currentTaskPrivileges = currentTaskPrivileges;     // 当前流程权限
        this.nextTaskPrivileges = nextTaskPrivileges;           // 下一流程权限
        this.unCheckFlag = 0;
        this.pageStatus = pageStatus;                           // 1:新增 2：编辑 3:审核 4:来源于通知
        this.pageListData = pageListData;                       // 从列表画面得到的数据结果（用于前后翻页）
        this.returnUrl = returnUrl;
        this.fetchDataUrl = fetchDataUrl;
        this.saveUrl = saveUrl;
        this.exportUrl = exportUrl;
        this.printUrl = printUrl;
        this.saveFlag = 0;                                     // 保存后是否继续增加标记
        this.hasFilterValue = false;                           // 控制过滤条件
        this.privateUserId = $("#UpdatedBy").val();            // 是否用私有用户控制保存等操作(默认的是更新者)
    }
    // 设置过滤控制条件
    SetHasFileterValue(boolData) {
        this.hasFilterValue = boolData;
    }
    DoBack() {
        location.assign(parent.basePath + this.returnUrl + '?flag=1');
    }
    PrevRecord() {
        if (this.pageListData.length > 0) {
            $("#ButNext").removeAttr("disabled");
            let index = $.inArray(this.dataId, this.pageListData);
            if (index === 0) {
                ShowErrorMessagePanel('已经到达第一条数据。');
                $("#ButPrev").attr("disabled", "disabled");
                $("#rec_cur_row").text("1");
                return;
            }
            this.dataId = this.pageListData[index - 1];
            $("#rec_cur_row").text(index);
            this.PageInit();
        }
    }
    NextRecord() {
        if (this.pageListData.length > 0) {
            $("#ButPrev").removeAttr("disabled");
            let index = $.inArray(this.dataId, this.pageListData);
            if (index === this.pageListData.length - 1) {
                ShowErrorMessagePanel('已经到达最后一条数据。');
                $("#ButNext").attr("disabled", "disabled");
                $("#rec_cur_row").text(index + 1);
                return;
            }
            this.dataId = this.pageListData[index + 1];
            $("#rec_cur_row").text(index + 2);
            this.PageInit();
        }
    }
    OnPageLoad() {
        $("#search_btn").hide();                  // 编辑画面无需搜索，隐藏搜索按钮
        $("#form_data").data("changed", false);   // 初始化form数据提交状态
        // 用于判断表单是否有更改
        $('form').find('input, select, textarea').change(function () {
            $("#form_data").data("changed", true);
        });

        // 增加权限控制
        if ($("#ActionAcl_2").length === 0 || parseInt($("#ActionAcl_2").val() === 0)) {
            $("#ButNew").remove();
            $("#ButNewLines").remove();
            $(".act__add").remove();
        }
        // 保存、编辑权限控制
        if ($("#ActionAcl_3").length === 0 || parseInt($("#ActionAcl_3").val() === 0)) {
            $("#ButSave").remove();
            $("#ButSaveLines").remove();
            $(".act__save").remove();
        }
        // 删除权限控制
        if ($("#ActionAcl_4").length === 0 || parseInt($("#ActionAcl_4").val() === 0)) {
            $(".act__del").remove();
        }
        // 完成开关控制
        if ($("#ActionAcl_8").length === 0 || parseInt($("#ActionAcl_8").val() === 0)) {
            $("#ButOverSwitcher").remove();
        }
        // 编辑或者审核状态则显示数据，新增状态则处于新增初始
        if (parseInt(this.pageStatus) >= 2) {
            this.PageInit();
        } else {
            this.New();
        }
    }
    PageInit() {
        let _params = {};
        if (this.hasFilterValue === false) {
            _params['HeaderId'] = parseInt(this.dataId);
            _params['CurrentUserId'] = parseInt($("#UserId").val());
            _params['WorkFlowId'] = $("#WorkFlowId").val() === '' ? 0 : parseInt($("#WorkFlowId").val());
        } else {
            _params = this.GetFilterValue();
        }

        $.ajax({
            type: "POST",
            url: parent.basePath + this.fetchDataUrl,
            timeout: 30 * 1000,
            data: JSON.stringify(_params),
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            beforeSend: function () {
            }
        }).done(data => {
            this.FillData(data);
        }).fail(data => {
            $('#loading').hide();
            ajaxError(data, 1);
        }).always(() => {
        });
    }
    // 设置画面元素的状态
    SetPageElementStatus(callBackHide, callBackShow, autoAdjustHeight) {
        $(".switcher").hide();
        // 审核状态控制(即对当前节点有审核权限以及下一节点有审核权限的，显示审核按钮)
        if (parseInt(this.currentTaskPrivileges) === 1 || parseInt(this.nextTaskPrivileges) === 1) {
            $("#ButCheck").show();
        } else {
            $("#ButCheck").hide();
        }
        // 反审按钮控制
        if (parseInt(this.unCheckFlag) === 1) {
            $("#ButUnCheck").show();
        } else {
            $("#ButUnCheck").hide();
        }
        // 处在审核状态时进行隐藏设置
        if ($("#CheckedByName").length > 0 && $("#CheckedByName").val() !== "") {
            // 最终审核
            if (parseInt($("#CheckedStatus").val()) === 1) {
                $("#CheckedTip").removeClass().addClass("huzo_status").addClass("huzo_status__green");
                $("#CheckedTip").html("状态：已审核");
                $(".switcher").show();   // 只有最终审核后才显示完成控制开关
            } else {
                $("#CheckedTip").removeClass().addClass("huzo_status").addClass("huzo_status__yellow");
                $("#CheckedTip").html("状态：审核中");
            }
            callBackHide();
        } else {
            $("#CheckedTip").removeClass().addClass("huzo_status").addClass("huzo_status__red");
            $("#CheckedTip").html("状态：未审核");
            // 只有当前用户和管理员才有编辑权限
            if ((parseInt($("#UserId").val()) === parseInt(this.privateUserId)) || ($("#RoleName").val().indexOf("系统管理员") !== -1)) {
                // 处在被引用状态，也需要进行隐藏设置
                //if (parseInt($("#QuotedFlag").val()) > 0) {
                //    callBackHide();
                //} else {
                callBackShow();
                //}
            } else {
                callBackHide();
            }
        }
        // 自适应高度
        autoAdjustHeight();
        $('#loading').hide();
    }
    Save(callback) {
        //step 1、进行页面验证，失败则返回
        if (!$("#form_data").valid())
            return;

        //step 2、执行处理
        $.ajax({
            type: "POST",
            url: parent.basePath + this.saveUrl,
            timeout: 30 * 1000,
            data: this.GetEntityData(),
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            beforeSend: () => {
            }
        }).done(data => {
            callback(data, this);
            // 保存后变成增加状态
            if (parseInt(this.saveFlag) === 1) {
                this.New();
            }
            $("#form_data").data("changed", false);   // 重新初始化
            ShowSuccessMessagePanel("保存成功。");
        }).fail(data => {
            ajaxError(data, 1);
        }).always(( ) => {
            this.saveFlag = 0;
        });
    }
    New() {
        // 判断当前form是否有改变
        if ($("#form_data").data("changed")) {
            showModal(370, 140, '系统信息', '', null, null, 1, "数据已经更新，是否需要保存？", () => {
                this.saveFlag = 1;
                this.Save();    // 表示保存后再增加
            }, () => (this.OnNew()));
        } else {
            this.OnNew();
        }
    }
    OnNew() {
        $("#form_data").data("changed", false);   // 重新初始化

        // 清空表单内容，准备下一个记录
        $(':input', '#form_data').not(':button, :submit, :reset, :hidden')
                .val('').removeAttr('checked').removeAttr('selected');
        $('#form_data')[0].reset();
        $(".error").removeClass("error");
        $(".tooltip").remove();
        $("img.errMsgTooltip").remove();
        $('#form_data span.selectSpan').html('');

        // 默认设置一些值
        $("#UpdatedByName").val($("#UserName").val());
        $("#UpdatedDate").val(getCurrentDate());

        //　审核情况
        $("#ButCheck").hide();
        $("#ButUnCheck").hide();
        $("#ButSave").show();
        $("#CheckedTip").hide();
        // 流程审核状态为 0
        $('#CheckedStatus').val("0");
        $('#FlowOrderNo').val("0");

        $("#ButPrint").hide();
        $("#ButPrev").hide();
        $("#ButNext").hide();
        $("#rec_position").hide();
        this.pageStatus = 1;
        this.dataId = 0;
        $("#Action").val(1);

        $('#loading').hide();
    }
    // 审核
    DoCheck(callback) {
        let item = {};
        item['HeaderId'] = parseInt($("#HeaderId").val());
        item['WorkFlowId'] = parseInt($("#WorkFlowId").val());
        item['NodeOrder'] = parseInt($("#FlowOrderNo").val());
        item['CheckedBy'] = parseInt($("#UserId").val());
        item['IsCheckCurrentNode'] = this.currentTaskPrivileges === 0 ? 0 : 1;

        $.ajax({
            type: "POST",
            url: parent.basePath + this.checkUrl,
            timeout: 30 * 1000,
            data: JSON.stringify(item),
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            beforeSend: () => {
            }
        }).done(data => {
            let item = data.HeaderEntity;
            // 最后的审核人、审核日期
            $("#CheckedBy").val(item.checkedBy);
            $("#CheckedByName").val(item.checkedByName);
            $("#CheckedDate").val(item.checkedDate === null ? '' : item.checkedDate);
            $("#CheckedStatus").val(item.checkedStatus);
            $('#FlowOrderNo').val(item.flowOrderNo);
            this.currentTaskPrivileges = item.currentTaskPrivileges;
            this.nextTaskPrivileges = item.nextTaskPrivileges;
            this.unCheckFlag = item.unCheckFlag;

            callback(data, this);
        }).fail(function (data) {
            ajaxError(data, 1);
        }).always(function ( ) {
        });
    }
    // 反审
    Uncheck(callback) {
        let item = {};
        item['HeaderId'] = parseInt($("#HeaderId").val());
        item['WorkFlowId'] = parseInt($("#WorkFlowId").val());
        item['NodeOrder'] = parseInt($("#FlowOrderNo").val());
        item['CheckedBy'] = parseInt($("#UserId").val());

        $.ajax({
            type: "POST",
            url: parent.basePath + this.uncheckUrl,
            timeout: 30 * 1000,
            data: JSON.stringify(item),
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            beforeSend: () => {
            }
        }).done(data => {
            let item = data.HeaderEntity;
            // 最后的审核人、审核日期
            $("#CheckedBy").val(item.checkedBy);
            $("#CheckedByName").val(item.checkedByName);
            $("#CheckedDate").val(item.checkedDate === null ? '' : item.checkedDate);
            $("#CheckedStatus").val(item.checkedStatus);
            $('#FlowOrderNo').val(item.flowOrderNo);

            this.currentTaskPrivileges = item.currentTaskPrivileges;
            this.nextTaskPrivileges = item.nextTaskPrivileges;
            this.unCheckFlag = item.unCheckFlag;

            callback(data, this);
        }).fail(data => {
            ajaxError(data, 1);
        }).always(( ) => {
        });
    }
    // 导出到Excel
    DoExport(flag) {
        $("#export_post_form").attr("action", parent.basePath + this.exportUrl);
        $("#HeaderKey").val($("#HeaderId").val());
        $("#Flag").val(flag);
        $("#export_post_form").submit();
    }
    // 跳转到打印预览画面
    DoPrintPreview() {
        window.open(parent.basePath + this.printUrl + '?id=' + $("#HeaderId").val() );
    }
    Expand(callback) {
        $("#panelTop").show();
        $("div.data__table_wrapper").show();
        $("#hPanelSplitter").children().removeClass("fa-angle-double-down").addClass("fa-angle-double-up");
        $("#hPanelSplitter").attr("title", "隐藏主表");
        $("#panelSlave").css({top: 0});
        callback();
    }
    /* 折叠 */
    Collapse(callback) {
        $("#panelTop").hide();
        $("div.data__table_wrapper").hide();
        $("#hPanelSplitter").children().removeClass("fa-angle-double-up").addClass("fa-angle-double-down");
        $("#hPanelSplitter").attr("title", "显示主表");
        $("#panelSlave").css({"top": 10});
        callback();
    }
    DoAjax(data, url, callback, $obj) {
        $.ajax({
            type: "POST",
            url: parent.basePath + url,
            timeout: 30 * 1000,
            data: JSON.stringify(data),
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            beforeSend: () => {
                //showLoadmask();
                if ($obj && $obj.length > 0) {
                    $obj.attr("disabled", "disabled");  // 禁用按钮
                }
            }
        }).done(data => {
            if (callback) {
                callback(data, this);
            }
        }).fail(data => {
            ajaxError(data, 1);
        }).always(( ) => {
            //hideLoadmask();
            if ($obj && $obj.length > 0) {
                $obj.removeAttr("disabled");
            }
        });
    }
}

class BaseEditSlave {
    constructor(saveLinesUrl, exportUrl, printUrl) {
        this.saveLinesUrl = saveLinesUrl;
        this.exportUrl = exportUrl;
        this.printUrl = printUrl;
        this.rows = 0;                  // 明细共有多少行记录
        this.numCheckbox = 0;
    }
    SaveLines(url, callback, $obj) {
        $.ajax({
            type: "POST",
            url: parent.basePath + url,
            timeout: 30 * 1000,
            data: this.GetLinesData(),
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            beforeSend: () => {
                if ($obj && $obj.length > 0) {
                    $obj.attr("disabled", "disabled");  // 禁用按钮
                }
            }
        }).done(data => {
            if (callback) {
                callback(data, this);
            }
        }).fail(data => {
            ajaxError(data, 1);
        }).always(( ) => {
            if ($obj && $obj.length > 0) {
                $obj.removeAttr("disabled");
            }
        });
    }
    DeleteLines(params, url, callback, $obj) {
        showModal(350, 140, '确认删除', '', null, null, 1, '请问，确定要删除当前记录吗？', () => {
            $.ajax({
                type: "POST",
                async: false,
                url: parent.basePath + url,
                timeout: 30 * 1000,
                data: JSON.stringify(params),
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                beforeSend: () => {
                    if ($obj && $obj.length > 0) {
                        $obj.attr("disabled", "disabled");  // 禁用按钮
                    }
                }
            }).done(data => {
                if (callback) {
                    callback(data, this);
                }
            }).fail(data => {
                ajaxError(data, 1);
            }).always(( ) => {
                if ($obj && $obj.length > 0) {
                    $obj.removeAttr("disabled");
                }
            });
        });
    }
    // 批量删除
    BatchDeleteLines(url, callback, $obj) {
        showModal(350, 140, '确认删除', '', null, null, 1, '请问，确定要删除所选记录吗？', () => {
            $.ajax({
                type: "POST",
                url: parent.basePath + url,
                timeout: 30 * 1000,
                data: this.GetCheckedLinesData(),
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                beforeSend: () => {
                    if ($obj && $obj.length > 0) {
                        $obj.attr("disabled", "disabled");  // 禁用按钮
                    }
                }
            }).done(data => {
                if (callback) {
                    callback(data, this);
                }
            }).fail(data => {
                ajaxError(data, 1);
            }).always(( ) => {
                if ($obj && $obj.length > 0) {
                    $obj.removeAttr("disabled");
                }
            });
        });
    }
    DoCheckAll($self, checkBoxName) {
        let _name = "input[type='checkbox'][name='" + checkBoxName + "']";
        let _this = this;
        if ($self.is(":checked") === true) {
            $(_name).each(function () {
                $(this).prop('checked', true);
                _this.SetRowStatus($(this));
            });
        } else {
            $(_name).each(function () {
                $(this).prop("checked", false);
                _this.SetRowStatus($(this));
            });
        }
    }
    DoCheckRow($self, checkBoxName, $checkall) {
        let _name = "input[type='checkbox'][name='" + checkBoxName + "']:checked";
        let _checkedRows = $(_name).length;
        if (_checkedRows < this.numCheckbox) {
            $checkall.prop("checked", false);
        } else {
            $checkall.prop("checked", true);
        }
        this.SetRowStatus($self);
    }
    AdjustRowStatus($self, disablerow, enablerow) {
        let $row = $self.parent().parent().parent();
        if ($self.is(":checked") === true) {
            $row.addClass("row__selected");
            disablerow($row, $row.index());
        } else {
            $row.removeClass("row__selected");
            enablerow($row, $row.index());
        }
    }
    DoAjax(data, url, callback, $obj) {
        $.ajax({
            type: "POST",
            url: parent.basePath + url,
            timeout: 30 * 1000,
            data: JSON.stringify(data),
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            beforeSend: () => {
                if ($obj && $obj.length > 0) {
                    $obj.attr("disabled", "disabled");  // 禁用按钮
                }
            }
        }).done(data => {
            callback(data, this);
        }).fail(data => {
            ajaxError(data, 1);
        }).always(( ) => {
            if ($obj && $obj.length > 0) {
                $obj.removeAttr("disabled");
            }
        });
    }
}

class BaseEditPicture {
    constructor() {
        this.$activeLi = null;
    }
    DoFileUpload() {
        AjaxFileUpload('hzUploadFile', parent.basePath + '/fileUpload.html', this.fileId);
    }
    DeletePicture() {
        if (this.$activeLi === null) {
            showModal(350, 140, '确认删除', '', null, null, 4, '对不起，请选择一个要删除的图片。');
        } else
            showModal(350, 140, '确认删除', '', null, null, 1, '请问，确定要删除该图片吗？', () => {
                if (this.$activeLi !== null) {
                    let instance = {};
                    instance['linesId'] = this.$activeLi.attr("id");
                    instance['imageFileDir'] = this.$activeLi.attr("imageFileDir");
                    instance['imageFileName'] = this.$activeLi.attr("imageFileName");

                    $.ajax({
                        type: "POST",
                        url: parent.basePath + this.delUrl,
                        timeout: 30 * 1000,
                        data: JSON.stringify(instance),
                        contentType: "application/json; charset=utf-8",
                        dataType: "json",
                        beforeSend: () => {
                        }
                    }).done((data) => {
                        if (data > 0) {
                            this.$activeLi.remove();
                            this.$activeLi = null;
                        }
                    }).fail((data) => {
                        ajaxError(data, 1);
                    }).always(( ) => {
                    });
                }
            });
    }
    ViewPicture() {
        if (this.$activeLi !== null) {
            let picture_url = this.$activeLi.children("img").eq(0).attr("src");
            window.open(picture_url);
        }
    }
    // 得到图片数据
    GetPictureEntityData(imageUrl, imageFileDir, imageFileName) {
        let item = {};
        item['headerId'] = $("#HeaderId").val();
        item['imageUrl'] = imageUrl;
        item['imageFileDir'] = imageFileDir;
        item['imageFileName'] = imageFileName;

        return JSON.stringify(item);
    }
    // 文件上传后的处理，保存数据并显示图片
    OnFileUploadEnd(imageUrl, imageFileDir, imageFileName) {
        $.ajax({
            type: "POST",
            url: parent.basePath + this.saveUrl,
            timeout: 30 * 1000,
            data: this.GetPictureEntityData(imageUrl, imageFileDir, imageFileName),
            contentType: "application/json;charset=utf-8",
            dataType: "json",
            beforeSend: () => {
            }
        }).done((data) => {
            let _tmp = '';
            _tmp += '<li id="' + data.PictureId + '" imageFileDir="' + imageFileDir + '" imageFileName="' + imageFileName + '">';
            _tmp += '<img src="' + $("#PictureUrl").val() + "/" + imageUrl + '" alt="' + this.altStr + '" style="max-width:142px; max-height:110px;" />';
            _tmp += '</li>';
            this.$picList.append(_tmp);
            _tmp = '';
            this.OnClickPicture();
        }).fail((data) => {
            ajaxError(data, 1);
        }).always(( ) => {
        });
    }
    // 点击图片
    OnClickPicture() {
        this.$picList.find("li").click((event) => {
            if (this.$activeLi !== null) {
                this.$activeLi.removeClass("active");
            }
            this.$activeLi = $(event.target);
            this.$activeLi.addClass("active");
        });
    }
}